<template>
  <div class="product-inventory">
    <el-page-header @back="goBack" :title="product.name || '商品库存详情'">
      <template #content>
        <span class="page-header-title">商品库存详情</span>
      </template>
    </el-page-header>
    
    <div class="page-content" v-loading="loading">
      <!-- 商品基本信息 -->
      <el-card class="product-info-card">
        <template #header>
          <div class="card-header">
            <h3>商品信息</h3>
            <div class="header-actions">
              <el-button type="primary" @click="handleAdjustInventory" :disabled="!hasAdjustPermission">
                <el-icon><Edit /></el-icon>
                调整库存
              </el-button>
              <el-button type="primary" @click="refreshData">
                <el-icon><RefreshRight /></el-icon>
                刷新数据
              </el-button>
            </div>
          </div>
        </template>
        
        <div class="product-info" v-if="product.id">
          <el-row :gutter="20">
            <el-col :xs="24" :sm="8" :md="6" :lg="4">
              <div class="product-image-container">
                <el-image
                  :src="product.imageUrl || '/images/products/default.png'"
                  fit="cover"
                  class="product-image"
                >
                  <template #error>
                    <div class="image-slot">
                      <el-icon><Picture /></el-icon>
                    </div>
                  </template>
                </el-image>
              </div>
            </el-col>
            
            <el-col :xs="24" :sm="16" :md="18" :lg="20">
              <div class="product-details">
                <h2 class="product-name">{{ product.name }}</h2>
                <div class="product-meta">
                  <p><span class="label">商品分类：</span>{{ product.category?.name || '-' }}</p>
                  <p><span class="label">商品编码：</span>{{ product.sku || '-' }}</p>
                  <p><span class="label">销售价格：</span>¥{{ product.price?.toFixed(2) || '-' }}</p>
                  <p><span class="label">成本价格：</span>¥{{ product.costPrice?.toFixed(2) || '-' }}</p>
                </div>
              </div>
            </el-col>
          </el-row>
          
          <el-divider />
          
          <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" v-for="(item, index) in inventoryCards" :key="index">
              <el-card shadow="hover" class="inventory-stat-card">
                <div class="inventory-stat">
                  <div class="stat-label">{{ item.label }}</div>
                  <div class="stat-value" :class="item.class">{{ item.value }}</div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        
        <el-empty v-else description="未找到商品信息" />
      </el-card>
      
      <!-- 库存变动历史 -->
      <el-card class="movement-history-card">
        <template #header>
          <div class="card-header">
            <h3>库存变动历史</h3>
            <div class="header-actions">
              <el-date-picker
                v-model="dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                @change="handleDateRangeChange"
              />
            </div>
          </div>
        </template>
        
        <el-table
          :data="movementHistory"
          border
          stripe
          style="width: 100%"
          v-loading="historyLoading"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="adjustmentDate" label="日期" width="150">
            <template #default="scope">
              {{ formatDate(scope.row.adjustmentDate) }}
            </template>
          </el-table-column>
          <el-table-column prop="adjustmentType" label="类型" width="120">
            <template #default="scope">
              <el-tag :type="getAdjustmentTypeTag(scope.row.adjustmentType)">
                {{ getAdjustmentTypeText(scope.row.adjustmentType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="warehouse" label="仓库" width="150">
            <template #default="scope">
              {{ scope.row.warehouse?.name || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="adjustmentQuantity" label="调整数量" width="120">
            <template #default="scope">
              <span :class="{ 
                'text-success': scope.row.adjustmentQuantity > 0,
                'text-danger': scope.row.adjustmentQuantity < 0
              }">
                {{ scope.row.adjustmentQuantity > 0 ? '+' : '' }}{{ scope.row.adjustmentQuantity }}
                {{ product.stockUnit || '个' }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="beforeQuantity" label="调整前" width="120">
            <template #default="scope">
              {{ scope.row.beforeQuantity || 0 }} {{ product.stockUnit || '个' }}
            </template>
          </el-table-column>
          <el-table-column prop="afterQuantity" label="调整后" width="120">
            <template #default="scope">
              {{ scope.row.afterQuantity || 0 }} {{ product.stockUnit || '个' }}
            </template>
          </el-table-column>
          <el-table-column prop="operator" label="操作人" width="120">
            <template #default="scope">
              {{ scope.row.operator?.name || '-' }}
            </template>
          </el-table-column>
          <el-table-column prop="remarks" label="备注" min-width="200" show-overflow-tooltip />
        </el-table>
        
        <div class="pagination-container">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next, jumper"
            :total="historyTotal"
            :page-size="historyPageSize"
            :page-sizes="[10, 20, 50, 100]"
            :current-page="historyPage"
            @size-change="handleHistorySizeChange"
            @current-change="handleHistoryPageChange"
          />
        </div>
      </el-card>
    </div>
    
    <!-- 库存调整弹窗 -->
    <el-dialog
      v-model="adjustDialogVisible"
      title="库存调整"
      width="500px"
      :close-on-click-modal="false"
    >
      <div class="adjust-dialog-content">
        <div class="product-info-dialog">
          <div class="product-name">{{ product.name }}</div>
          <div class="product-stock">
            当前库存: {{ product.stockQuantity || 0 }} {{ product.stockUnit || '个' }}
          </div>
        </div>
        
        <el-form ref="adjustFormRef" :model="adjustForm" :rules="adjustRules" label-width="100px">
          <el-form-item label="仓库" prop="warehouseId">
            <el-select v-model="adjustForm.warehouseId" placeholder="选择仓库" style="width: 100%">
              <el-option
                v-for="warehouse in warehouses"
                :key="warehouse.id"
                :label="warehouse.name"
                :value="warehouse.id"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="调整类型" prop="adjustmentType">
            <el-select v-model="adjustForm.adjustmentType" placeholder="选择调整类型" style="width: 100%">
              <el-option :label="'入库调整'" :value="1" />
              <el-option :label="'出库调整'" :value="2" />
              <el-option :label="'损坏出库'" :value="3" />
              <el-option :label="'过期出库'" :value="4" />
              <el-option :label="'其他调整'" :value="5" />
            </el-select>
          </el-form-item>
          
          <el-form-item label="调整数量" prop="adjustmentQuantity">
            <el-input-number
              v-model="adjustForm.adjustmentQuantity"
              :precision="2"
              :step="1"
              :min="adjustmentMinValue"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item label="备注" prop="remarks">
            <el-input
              v-model="adjustForm.remarks"
              type="textarea"
              :rows="3"
              placeholder="请输入调整原因或备注"
            />
          </el-form-item>
        </el-form>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adjustDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdjustment" :loading="adjustSubmitting">
            确认调整
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  RefreshRight, 
  Edit,
  Picture
} from '@element-plus/icons-vue'
import { 
  getProductInventory, 
  getAllWarehouses, 
  adjustInventory,
  getInventoryMovements
} from '@/api/inventory'

const route = useRoute()
const router = useRouter()
const productId = route.params.id

// 页面数据
const loading = ref(false)
const historyLoading = ref(false)
const product = ref({})
const warehouses = ref([])
const movementHistory = ref([])
const historyTotal = ref(0)
const historyPage = ref(1)
const historyPageSize = ref(10)
const dateRange = ref([])

// 权限判断
const hasAdjustPermission = ref(true) // 实际项目中应该根据用户权限判断

// 计算库存相关的显示卡片
const inventoryCards = computed(() => {
  return [
    {
      label: '当前库存',
      value: `${product.value.stockQuantity || 0} ${product.value.stockUnit || '个'}`,
      class: ''
    },
    {
      label: '库存预警值',
      value: product.value.minimumStock ? `${product.value.minimumStock} ${product.value.stockUnit || '个'}` : '未设置',
      class: ''
    },
    {
      label: '库存状态',
      value: getStatusText(product.value),
      class: getStatusClass(product.value)
    },
    {
      label: '库存金额',
      value: product.value.costPrice ? 
        `¥${(product.value.costPrice * (product.value.stockQuantity || 0)).toFixed(2)}` : 
        '未设置成本价',
      class: ''
    }
  ]
})

// 计算调整数量的最小值
const adjustmentMinValue = computed(() => {
  // 出库类型调整，限制不能超过当前库存
  if (adjustForm.adjustmentType > 1) {
    return -product.value.stockQuantity || -9999
  }
  return -9999 // 入库不限制
})

// 获取状态文本
const getStatusText = (product) => {
  if (!product) return '未知'
  
  if (product.stockStatus === 'out_of_stock' || product.stockQuantity === 0 || product.stockQuantity === null) {
    return '缺货'
  } else if (product.stockStatus === 'warning' || (product.minimumStock && product.stockQuantity < product.minimumStock)) {
    return '预警'
  } else {
    return '正常'
  }
}

// 获取状态样式类
const getStatusClass = (product) => {
  if (!product) return ''
  
  if (product.stockStatus === 'out_of_stock' || product.stockQuantity === 0 || product.stockQuantity === null) {
    return 'text-danger'
  } else if (product.stockStatus === 'warning' || (product.minimumStock && product.stockQuantity < product.minimumStock)) {
    return 'text-warning'
  } else {
    return 'text-success'
  }
}

// 获取调整类型文本
const getAdjustmentTypeText = (type) => {
  switch (type) {
    case 1: return '入库调整'
    case 2: return '出库调整'
    case 3: return '损坏出库'
    case 4: return '过期出库'
    case 5: return '其他调整'
    default: return '未知'
  }
}

// 获取调整类型标签样式
const getAdjustmentTypeTag = (type) => {
  switch (type) {
    case 1: return 'success'
    case 2: return 'danger'
    case 3: return 'danger'
    case 4: return 'danger'
    case 5: return 'info'
    default: return ''
  }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 返回上一页
const goBack = () => {
  router.go(-1)
}

// 日期范围变更
const handleDateRangeChange = () => {
  historyPage.value = 1
  fetchMovementHistory()
}

// 分页处理
const handleHistorySizeChange = (val) => {
  historyPageSize.value = val
  historyPage.value = 1
  fetchMovementHistory()
}

const handleHistoryPageChange = (val) => {
  historyPage.value = val
  fetchMovementHistory()
}

// 库存调整相关
const adjustDialogVisible = ref(false)
const adjustSubmitting = ref(false)
const adjustFormRef = ref(null)
const adjustForm = reactive({
  productId: null,
  warehouseId: null,
  adjustmentType: 1,
  adjustmentQuantity: 1,
  remarks: ''
})

const adjustRules = {
  warehouseId: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
  adjustmentType: [
    { required: true, message: '请选择调整类型', trigger: 'change' }
  ],
  adjustmentQuantity: [
    { required: true, message: '请输入调整数量', trigger: 'blur' }
  ]
}

// 调整库存
const handleAdjustInventory = () => {
  adjustForm.productId = product.value.id
  adjustForm.warehouseId = warehouses.value.length > 0 ? warehouses.value[0].id : null
  adjustForm.adjustmentType = 1
  adjustForm.adjustmentQuantity = 1
  adjustForm.remarks = ''
  adjustDialogVisible.value = true
}

// 提交库存调整
const submitAdjustment = async () => {
  if (!adjustFormRef.value) return
  
  await adjustFormRef.value.validate(async (valid) => {
    if (valid) {
      adjustSubmitting.value = true
      
      try {
        // 调整库存
        const response = await adjustInventory({
          productId: adjustForm.productId,
          warehouseId: adjustForm.warehouseId,
          adjustmentType: adjustForm.adjustmentType,
          // 如果是出库类型(2-5)且数量为正数，则转为负数
          adjustmentQuantity: adjustForm.adjustmentType > 1 && adjustForm.adjustmentQuantity > 0 
            ? -adjustForm.adjustmentQuantity 
            : adjustForm.adjustmentQuantity,
          remarks: adjustForm.remarks
        })
        
        if (response.success) {
          ElMessage.success('库存调整成功')
          adjustDialogVisible.value = false
          refreshData() // 刷新数据
        } else {
          ElMessage.error(response.message || '库存调整失败')
        }
      } catch (error) {
        console.error('库存调整失败:', error)
        ElMessage.error('库存调整失败')
      } finally {
        adjustSubmitting.value = false
      }
    }
  })
}

// 获取库存变动历史
const fetchMovementHistory = async () => {
  if (!productId) return
  
  historyLoading.value = true
  try {
    const params = {
      productId,
      page: historyPage.value,
      pageSize: historyPageSize.value
    }
    
    if (dateRange.value && dateRange.value.length === 2) {
      params.startDate = dateRange.value[0]
      params.endDate = dateRange.value[1]
    }
    
    const response = await getInventoryMovements(params)
    
    if (response.success) {
      movementHistory.value = response.data.records || []
      historyTotal.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取库存变动历史失败')
    }
  } catch (error) {
    console.error('获取库存变动历史失败:', error)
    ElMessage.error('获取库存变动历史失败')
  } finally {
    historyLoading.value = false
  }
}

// 刷新数据
const refreshData = async () => {
  if (!productId) {
    ElMessage.error('商品ID不能为空')
    return
  }
  
  loading.value = true
  try {
    // 获取商品库存信息
    const response = await getProductInventory(productId)
    
    if (response.success) {
      product.value = response.data || {}
    } else {
      ElMessage.error(response.message || '获取商品库存信息失败')
    }
    
    // 获取仓库列表
    const warehouseResponse = await getAllWarehouses()
    if (warehouseResponse.success) {
      warehouses.value = warehouseResponse.data || []
    }
    
    // 获取库存变动历史
    fetchMovementHistory()
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 组件挂载时获取数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.product-inventory {
  padding-bottom: 20px;
}

.page-header-title {
  font-size: 18px;
  font-weight: bold;
}

.page-content {
  margin-top: 20px;
}

.product-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.product-image-container {
  width: 100%;
  display: flex;
  justify-content: center;
}

.product-image {
  width: 100%;
  max-width: 150px;
  height: auto;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.product-details {
  padding: 10px 0;
}

.product-name {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 24px;
}

.product-meta {
  margin-bottom: 20px;
}

.product-meta p {
  margin: 8px 0;
}

.label {
  font-weight: bold;
  margin-right: 5px;
  color: #606266;
}

.inventory-stat-card {
  margin-bottom: 20px;
}

.inventory-stat {
  text-align: center;
  padding: 10px 0;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 10px;
}

.stat-value {
  font-size: 22px;
  font-weight: bold;
}

.text-success {
  color: #67C23A;
}

.text-warning {
  color: #E6A23C;
}

.text-danger {
  color: #F56C6C;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
}

.product-info-dialog {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.product-info-dialog .product-name {
  font-size: 18px;
  margin-bottom: 8px;
}

.product-info-dialog .product-stock {
  font-size: 14px;
  color: #606266;
}
</style> 